<template>
  <div class="training-config">
    <h2>训练参数配置</h2>
    <div class="form-group">
      <label>Replica Group ID</label>
      <input type="number" v-model.number="groupId" />
    </div>
    <div class="form-group">
      <label>Rank (节点编号)</label>
      <input type="number" v-model.number="rank" />
    </div>
    <div class="form-group">
      <label>Learning Rate</label>
      <input type="number" step="0.001" v-model.number="learningRate" />
    </div>
    <div class="form-group">
      <label>Batch Size</label>
      <input type="number" v-model.number="batchSize" />
    </div>
    <button @click="handleSave" :disabled="isSaving">
      {{ isSaving ? '保存中...' : '保存配置' }}
    </button>
    <div v-if="message" :class="['message', message.type]">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useTrainingStore } from '../stores/training'

const trainingStore = useTrainingStore()

const groupId = ref(0)
const rank = ref(0)
const learningRate = ref(0.001)
const batchSize = ref(32)
const isSaving = ref(false)
const message = ref(null)

const handleSave = async () => {
  isSaving.value = true
  try {
    const success = trainingStore.saveConfig(
      groupId.value,
      rank.value,
      learningRate.value,
      batchSize.value
    )
    
    message.value = {
      text: success 
        ? `已更新 Group ${groupId.value} 的 Rank ${rank.value}：LR=${learningRate.value}, Batch=${batchSize.value}`
        : `未找到 Group ${groupId.value} 的 Rank ${rank.value}`,
      type: success ? 'success' : 'warning'
    }
  } catch (error) {
    message.value = {
      text: '请输入合法的数字（Group ID、Rank、LR、Batch）',
      type: 'error'
    }
  } finally {
    isSaving.value = false
    setTimeout(() => message.value = null, 3000)
  }
}
</script>

<style scoped>
.training-config {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

/* Add this to make form fill available height */
.training-config > :not(button):not(.message) {
  flex: 0 0 auto;
}

.training-config > button {
  margin-top: 20px;
}

h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 1.2em;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

label {
  font-weight: bold;
}

input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.message {
  padding: 10px;
  border-radius: 4px;
  margin-top: 10px;
}

.message.success {
  background-color: #dff0d8;
  color: #3c763d;
}

.message.warning {
  background-color: #fcf8e3;
  color: #8a6d3b;
}

.message.error {
  background-color: #f2dede;
  color: #a94442;
}
</style>